package dao

import (
	"errors"
	"log"
	"k8s-platform/db"
	"k8s-platform/model"
)

var Workflow workflow

type workflow struct {}

// 定义列表返回内容。 Items是WorKflow元素列表 Total为元素数量
type WorkFlowResp struct {
	Items []*model.WorKflow `json:"items"`
	Total int `json:"total"`
}

//获取列表分页查询
func (w *workflow)GetList(name string,page ,limit int) (data *WorkFlowResp,err error)  {
	//定义分页数据的其实未知
	startSet := (page - 1) * limit
	//定义数据库查询返回内容
	var workflowList []*model.WorKflow
	//数据库查询 Limit用于限制条数 Offset方法设置起始位置  -----id desc以id倒叙排列
	tx := db.GORM.Where("name like ?","%"+ name +"%").Limit(limit).Offset(startSet).Order("id desc").Find(&workflowList)
	//gorm 默认会把空数据也放到err中 故要排除空数据的情况
	if tx.Error != nil && tx.Error.Error() != "record not found" {
		log.Println("获取Workflow列表失败",tx.Error.Error())
		return nil,errors.New("获取Workflow列表失败" + tx.Error.Error())
	}
	return &WorkFlowResp{
		Items: workflowList,
		Total: len(workflowList),
	},nil
}

//获取单条
func (w *workflow)GetById(id int) (workflow *model.WorKflow,err error) {
	workflow = &model.WorKflow{}
	tx := db.GORM.Where("id = ?",id).First(&workflow)
	if tx.Error != nil && tx.Error.Error() != "record not found" {
		log.Println("获取Workflow失败",tx.Error.Error())
		return nil,errors.New("获取Workflow失败" + tx.Error.Error())
	}
	return workflow,nil
}

//新增
func (w *workflow) Add(workflow *model.WorKflow) (err error)  {
	tx := db.GORM.Create(&workflow)
	if tx.Error != nil {
		log.Println("创建Workflow失败",tx.Error.Error())
		return errors.New("创建Workflow失败" + tx.Error.Error())
	}
	return nil
}


//表数据删除
/*软删除 db.GORM.Delete("id = ?",id) 软删除执行的是update语句 将deleted_at字段设置为时间  gorm默认是软删除
实际执行语句是 UPDATE `workflow` set `deleted_at` = '2022-08-12 22:32:11' where `id` in ('1'

硬删除 db.gorm.Unscoped().Delete("id = ?",id)直接从表中删除这条数据
实际执行语句 DELETE from `workflow` where `id` in ('1')
*/
func (w *workflow)DelById(id int) (err error) {
	tx := db.GORM.Where("id = ?",id ).Delete(&model.WorKflow{})
	if tx.Error != nil {
		log.Println("删除Workflow失败",tx.Error.Error())
		return errors.New("删除Workflow失败" + tx.Error.Error())
	}
	return nil
}






















